package com.ran.java_gobang.advice;

import com.ran.java_gobang.game.request.UserRegisterRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-08-31
 * Time: 16:54
 */
@ControllerAdvice
@Slf4j
@ResponseBody
public class ExceptionAdvice {
    @ExceptionHandler
    public void exceptionHandlere(Exception e) {
        log.error("统一处理异常,e: ",e);
    }

    @ExceptionHandler
    public UserRegisterRequest exceptionHandlere(MethodArgumentNotValidException/*参数校验异常*/ e) {
        String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
        log.error("发生异常,e: {}",e.getMessage());
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setMessage(defaultMessage);
        return userRegisterRequest;
    }

    @ExceptionHandler
    public UserRegisterRequest exceptionHandlere(RuntimeException e) {
        log.error("发生异常,e: {}",e.getMessage());
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setMessage(e.getMessage());
        return userRegisterRequest;
    }
}
